package cn.kailangtu.myapplication.view;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.kailangtu.myapplication.R;
import cn.kailangtu.myapplication.events.CloseKeyboardEvent;
import cn.kailangtu.myapplication.events.OpenKeyboardEvent;
import cn.kailangtu.myapplication.events.eventData.KeyboardInputType;

public class VirtualKeyboardFragment extends Fragment {
    // 输入类型常量

    // 输入规则参数
    private KeyboardInputType inputType = KeyboardInputType.PASSWORD;
    private int minLength = 0;
    private int maxLength = Integer.MAX_VALUE;
    private double minValue = Double.MIN_VALUE;
    private double maxValue = Double.MAX_VALUE;
    private String initialValue = "";
    private int requestCode;

    // 视图组件
    private TextView inputDisplay;
    private TextView inputRange;
    private View letterKeyboard;
    private View symbolKeyboard;
    private boolean isUpperCase = false;
    private boolean isLetterMode = true;
    private String currentInput = "";

    private Object caller;

    // 回调接口
    private OnKeyboardInteractionListener listener;

    // 静态工厂方法，用于创建Fragment实例并传递参数
    public static VirtualKeyboardFragment newInstance(KeyboardInputType inputType, int requestCode) {
        VirtualKeyboardFragment fragment = new VirtualKeyboardFragment();
        Bundle args = new Bundle();
        args.putSerializable("inputType", inputType);
        args.putInt("requestCode", requestCode);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            inputType = (KeyboardInputType) getArguments().get("inputType");
            requestCode = getArguments().getInt("requestCode");
        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 加载布局
        View rootView = inflater.inflate(R.layout.fragment_virtual_keyboard, container, false);

        // 初始化视图
        inputDisplay = rootView.findViewById(R.id.keyboard_input_display);
        inputRange = rootView.findViewById(R.id.keyboard_input_range);
        letterKeyboard = rootView.findViewById(R.id.letter_keyboard);
        symbolKeyboard = rootView.findViewById(R.id.symbol_keyboard);

        // 设置初始值
        currentInput = initialValue;
        updateInputDisplay();

        // 初始化字母键盘按钮
        initLetterKeyboardButtons(rootView);

        // 初始化符号键盘按钮
        initSymbolKeyboardButtons(rootView);

        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 视图创建完成后，更新inputRange
        if (inputRange != null) {
            if (inputType == KeyboardInputType.STRING || inputType == KeyboardInputType.PASSWORD) {
                inputRange.setText("输入长度范围：" + this.minLength + "--" + this.maxLength);
            } else {
                inputRange.setText("输入值范围：" + String.format("%.2f",this.minValue)+ "--" + String.format("%.2f",this.maxValue));
            }
        }
    }

    // 设置输入规则
    public void setInputRules(int minLength, int maxLength, double minValue, double maxValue) {
        this.minLength = minLength;
        this.maxLength = maxLength;
        this.minValue = minValue;
        this.maxValue = maxValue;

    }



    // 设置初始值
    public void setInitialValue(String value) {
        this.initialValue = value;
        this.currentInput = value;
        if (inputDisplay != null) {
            updateInputDisplay();
        }

    }

    // 初始化字母键盘按钮
    private void initLetterKeyboardButtons(View rootView) {
        // 字母按钮
        setupLetterButton(rootView, R.id.letter_btn_q, "q");
        setupLetterButton(rootView, R.id.letter_btn_w, "w");
        setupLetterButton(rootView, R.id.letter_btn_e, "e");
        setupLetterButton(rootView, R.id.letter_btn_r, "r");
        setupLetterButton(rootView, R.id.letter_btn_t, "t");
        setupLetterButton(rootView, R.id.letter_btn_y, "y");
        setupLetterButton(rootView, R.id.letter_btn_u, "u");
        setupLetterButton(rootView, R.id.letter_btn_i, "i");
        setupLetterButton(rootView, R.id.letter_btn_o, "o");
        setupLetterButton(rootView, R.id.letter_btn_p, "p");

        setupLetterButton(rootView, R.id.letter_btn_a, "a");
        setupLetterButton(rootView, R.id.letter_btn_s, "s");
        setupLetterButton(rootView, R.id.letter_btn_d, "d");
        setupLetterButton(rootView, R.id.letter_btn_f, "f");
        setupLetterButton(rootView, R.id.letter_btn_g, "g");
        setupLetterButton(rootView, R.id.letter_btn_h, "h");
        setupLetterButton(rootView, R.id.letter_btn_j, "j");
        setupLetterButton(rootView, R.id.letter_btn_k, "k");
        setupLetterButton(rootView, R.id.letter_btn_l, "l");

        // Shift键
        Button shiftBtn = rootView.findViewById(R.id.letter_btn_shift);
        shiftBtn.setOnClickListener(v -> toggleCase());

        setupLetterButton(rootView, R.id.letter_btn_z, "z");
        setupLetterButton(rootView, R.id.letter_btn_x, "x");
        setupLetterButton(rootView, R.id.letter_btn_c, "c");
        setupLetterButton(rootView, R.id.letter_btn_v, "v");
        setupLetterButton(rootView, R.id.letter_btn_b, "b");
        setupLetterButton(rootView, R.id.letter_btn_n, "n");
        setupLetterButton(rootView, R.id.letter_btn_m, "m");

        // 退格键
        Button backspaceBtn = rootView.findViewById(R.id.letter_btn_backspace);
        backspaceBtn.setOnClickListener(v -> handleBackspace());

        // 空格键
        Button spaceBtn = rootView.findViewById(R.id.letter_btn_space);
        spaceBtn.setOnClickListener(v -> handleInput(" "));

        // 切换到符号键盘
        Button symbolSwitchBtn = rootView.findViewById(R.id.letter_btn_switch);
        symbolSwitchBtn.setOnClickListener(v -> switchToSymbolKeyboard());

        // 完成按钮
        Button doneBtn = rootView.findViewById(R.id.letter_btn_done);
        doneBtn.setOnClickListener(v -> handleDone());

        // 取消按钮
        Button cancelBtn = rootView.findViewById(R.id.letter_btn_cancel);
        cancelBtn.setOnClickListener(v -> handleCancel());
    }

    // 初始化符号键盘按钮
    private void initSymbolKeyboardButtons(View rootView) {
        // 数字和符号按钮
        setupSymbolButton(rootView, R.id.symbol_btn_1, "1");
        setupSymbolButton(rootView, R.id.symbol_btn_2, "2");
        setupSymbolButton(rootView, R.id.symbol_btn_3, "3");
        setupSymbolButton(rootView, R.id.symbol_btn_4, "4");
        setupSymbolButton(rootView, R.id.symbol_btn_5, "5");
        setupSymbolButton(rootView, R.id.symbol_btn_6, "6");
        setupSymbolButton(rootView, R.id.symbol_btn_7, "7");
        setupSymbolButton(rootView, R.id.symbol_btn_8, "8");
        setupSymbolButton(rootView, R.id.symbol_btn_9, "9");
        setupSymbolButton(rootView, R.id.symbol_btn_0, "0");

        setupSymbolButton(rootView, R.id.symbol_btn_dot, ".");
        setupSymbolButton(rootView, R.id.symbol_btn_minus, "-");
        setupSymbolButton(rootView, R.id.symbol_btn_plus, "+");
        setupSymbolButton(rootView, R.id.symbol_btn_star, "*");
        setupSymbolButton(rootView, R.id.symbol_btn_slash, "/");
        setupSymbolButton(rootView, R.id.symbol_btn_percent, "%");
        setupSymbolButton(rootView, R.id.symbol_btn_lparen, "(");
        setupSymbolButton(rootView, R.id.symbol_btn_rparen, ")");
        setupSymbolButton(rootView, R.id.symbol_btn_equals, "=");

        // 退格键
        Button backspaceBtn = rootView.findViewById(R.id.symbol_btn_backspace);
        backspaceBtn.setOnClickListener(v -> handleBackspace());

        // 切换到字母键盘
        Button letterSwitchBtn = rootView.findViewById(R.id.symbol_btn_switch);
        letterSwitchBtn.setOnClickListener(v -> switchToLetterKeyboard());

        // 完成按钮
        Button doneBtn = rootView.findViewById(R.id.symbol_btn_done);
        doneBtn.setOnClickListener(v -> handleDone());

        // 取消按钮
        Button cancelBtn = rootView.findViewById(R.id.symbol_btn_cancel);
        cancelBtn.setOnClickListener(v -> handleCancel());
    }

    // 设置字母按钮
    private void setupLetterButton(View rootView, int buttonId, String character) {
        Button button = rootView.findViewById(buttonId);
        button.setText(character);
        button.setOnClickListener(v -> handleInput(character));
    }

    // 设置符号按钮
    private void setupSymbolButton(View rootView, int buttonId, String character) {
        Button button = rootView.findViewById(buttonId);
        button.setText(character);
        button.setOnClickListener(v -> handleInput(character));
    }

    // 处理输入
    private void handleInput(String character) {
        // 根据当前大小写状态转换字符
        String inputChar = isUpperCase ? character.toUpperCase() : character;

        // 检查输入是否符合规则
        if (isInputValid(inputChar)) {
            currentInput += inputChar;
            updateInputDisplay();
        }
    }

    // 处理退格
    private void handleBackspace() {
        if (currentInput.length() > 0) {
            currentInput = currentInput.substring(0, currentInput.length() - 1);
            updateInputDisplay();
        }
    }

    // 切换大小写
    private void toggleCase() {
        isUpperCase = !isUpperCase;
        updateLetterCase();
    }

    // 更新字母大小写显示
    private void updateLetterCase() {
        // 这里需要更新所有字母按钮的大小写状态
        // 实际实现中需要遍历所有字母按钮并更新文本
    }

    // 切换到符号键盘
    private void switchToSymbolKeyboard() {
        letterKeyboard.setVisibility(View.GONE);
        symbolKeyboard.setVisibility(View.VISIBLE);
        isLetterMode = false;
    }

    // 切换到字母键盘
    private void switchToLetterKeyboard() {
        symbolKeyboard.setVisibility(View.GONE);
        letterKeyboard.setVisibility(View.VISIBLE);
        isLetterMode = true;
    }

    // 处理完成
    private void handleDone() {
        // 验证最终输入是否符合所有规则
        if (isFinalInputValid()) {
            if (listener != null) {
                listener.onKeyboardDone(currentInput, requestCode);
            }
            // 也可以通过EventBus发送事件
            EventBus.getDefault().post(new CloseKeyboardEvent(currentInput, true, requestCode));
            currentInput = "";
            initialValue  = "";
            inputDisplay.setText("");
        }
    }

    // 处理取消
    private void handleCancel() {
        if (listener != null) {
            listener.onKeyboardCancel(requestCode);
        }
        // 也可以通过EventBus发送事件
        EventBus.getDefault().post(new CloseKeyboardEvent("", false, requestCode));
        currentInput = "";
        initialValue = "";
        inputDisplay.setText("");
    }

    // 更新输入显示
    private void updateInputDisplay() {

        if (inputType == KeyboardInputType.PASSWORD) {
            // 密码类型显示星号
            inputDisplay.setText(getPasswordMask(currentInput.length()));
        } else {
            inputDisplay.setText(currentInput);
        }
    }

    // 获取密码掩码
    private String getPasswordMask(int length) {
        StringBuilder mask = new StringBuilder();
        for (int i = 0; i < length; i++) {
            mask.append('*');
        }
        return mask.toString();
    }

    // 检查输入是否有效
    private boolean isInputValid(String newChar) {
        // 检查长度限制
        if (currentInput.length() + newChar.length() > maxLength) {
            return false;
        }

        // 根据输入类型检查

            if (inputType == KeyboardInputType.INTEGER) {
                return isValidIntegerInput(newChar);
            } else if (inputType == KeyboardInputType.REAL) {
                return isValidRealInput(newChar);
            } else if (inputType == KeyboardInputType.PASSWORD || inputType == KeyboardInputType.STRING) {

            }

        return true;

    }

    // 检查整数输入是否有效
    private boolean isValidIntegerInput(String newChar) {
        // 实现整数输入验证逻辑
        // 检查是否为数字或负号（只能在开头出现一次）
        if (!newChar.matches("-?\\d+")) {
            return false;
        }

        // 检查负号是否已经存在或不在开头
        if (newChar.equals("-")) {
            return currentInput.isEmpty();
        }

        return true;
    }

    // 检查实数输入是否有效
    private boolean isValidRealInput(String newChar) {
        // 实现实数输入验证逻辑
        if (newChar.equals(".")) {
            // 检查是否已经有小数点
            return !currentInput.contains(".");
        }

        if (newChar.equals("-")) {
            // 负号只能在开头
            return currentInput.isEmpty();
        }

        // 检查是否为数字
        return newChar.matches("\\d+");
    }

    // 检查最终输入是否有效
    private boolean isFinalInputValid() {
        // 检查长度限制
        if (currentInput.length() < minLength || currentInput.length() > maxLength) {
            return false;
        }

        // 检查数值范围
        if (inputType == KeyboardInputType.INTEGER) {
            try {
                int value = Integer.parseInt(currentInput);
                return value >= minValue && value <= maxValue;
            } catch (NumberFormatException e) {
                return false;
            }
        } else if (inputType == KeyboardInputType.REAL) {
            try {
                double value = Double.parseDouble(currentInput);
                return value >= minValue && value <= maxValue;
            } catch (NumberFormatException e) {
                return false;
            }
        }

        return true;
    }

    // 设置回调监听器
    public void setOnKeyboardInteractionListener(OnKeyboardInteractionListener listener) {
        this.listener = listener;
    }

    // 键盘交互回调接口
    public interface OnKeyboardInteractionListener {
        void onKeyboardDone(String result, int requestCode);
        void onKeyboardCancel(int requestCode);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(OpenKeyboardEvent event)
    {

    }
}

